package net.wanho.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import net.wanho.constant.UserConstant;
import net.wanho.dto.AssignRoleDTO;
import net.wanho.mapper.RoleMapper;
import net.wanho.po.UserRole;
import net.wanho.service.UserRoleService;
import net.wanho.mapper.UserRoleMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【user_role(用户角色表)】的数据库操作Service实现
* @createDate 2025-04-28 11:41:59
*/
@Service
@RequiredArgsConstructor
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole>
    implements UserRoleService{

    private final RedisTemplate<String, Object> redisTemplate;
    private final RoleMapper roleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignRole(AssignRoleDTO assignRoleDTO) {
        // 1. 删除用户原有的角色
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>(); // 删除条件
        wrapper.eq("user_id", assignRoleDTO.getUserId());
        this.remove(wrapper);

        // 2. 添加新的角色
        if (!ObjectUtil.isEmpty(assignRoleDTO.getRoleCheckList())) {
            List<UserRole> userRoles = assignRoleDTO.getRoleCheckList().stream()
                    .map(roleName -> {
                        // 根据角色名称获取角色ID
                        Integer roleId = roleMapper.selectByName(roleName).getRoleId();
                        UserRole userRole = new UserRole();
                        userRole.setUserId(assignRoleDTO.getUserId());
                        userRole.setRoleId(roleId);
                        return userRole;
                    })
                    .collect(Collectors.toList());

            this.saveBatch(userRoles);
        }

        // 3. 清除Redis中的用户菜单缓存
        redisTemplate.delete(UserConstant.MENU_PREFIX + assignRoleDTO.getUserId());
    }

    @Override
    public void removeByUserId(Integer id) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id);
        this.remove(wrapper);
    }
}




